// CountWordsAndImages does an HTTP GET request for the HTML
// document url and returns the number of words and images in it.
package main

import (
	"bufio"
	"fmt"
	"net/http"
	"os"
	"strings"

	"golang.org/x/net/html"
)

func main() {
	fmt.Println(CountWordsAndImages(os.Args[1]))
}

func CountWordsAndImages(url string) (words, images int, err error) {
	resp, err := http.Get(url)
	if err != nil {
		return
	}
	doc, err := html.Parse(resp.Body)
	resp.Body.Close()
	if err != nil {
		err = fmt.Errorf("parsing HTML: %s", err)
		return
	}
	words, images = countWordsAndImages(doc)
	return
}

func countWordsAndImages(n *html.Node) (words, images int) {
	if n.Type == html.ElementNode && n.Data == "img" {
		images++
	}
	if n.Type == html.TextNode && n.Data != "" && n.Parent.Data != "script" && n.Parent.Data != "style" {
		stringReader := strings.NewReader(n.Data)

		input := bufio.NewScanner(stringReader)
		input.Split(bufio.ScanWords)
		for input.Scan() {
			words++
		}
	}
	if n.FirstChild != nil {
		word, image := countWordsAndImages(n.FirstChild)
		words += word
		images += image
	}
	if n.NextSibling != nil {
		word, image := countWordsAndImages(n.NextSibling)
		words += word
		images += image
	}
	return
}
